﻿Imports System
Imports System.Web
Imports System.Net
Imports System.IO
Imports NEvoWeb.Modules.NB_Store.SharedFunctions
Imports System.Collections.Specialized
Imports System.Text
Imports Uol.PagSeguro

Namespace NEvoWeb.Modules.NB_Store.Gateway
    Public Class GatewayPagSeguro
        Inherits GatewayInterface
        Public Overrides Function GetButtonHtml(ByVal PortalID As Integer, ByVal OrderID As Integer, ByVal Lang As String) As String
            Dim strHTML As String = ""
            Dim objSCtrl As New SettingsController
            Dim objSInfo As NB_Store_SettingsInfo
            'get the gateway settings from the NB_Store settings table
            objSInfo = objSCtrl.GetSetting(PortalID, "PagSeguro.gateway", Lang)
            If Not objSInfo Is Nothing Then
                'Move the xml format settingn into the a hashtable so we can use it easily.
                Dim setParams As Hashtable = createSettingsTable(objSInfo.SettingValue)
                'Build Html to display the payment button.
                strHTML = "<INPUT TYPE=IMAGE NAME=PAGSEGUROGATEWAY BORDER=0 SRC=""" & setParams("ButtonImageURL") & """name=""submit"" alt=""Pague com PagSeguro - é rápido, grátis e seguro!"" />"
            End If
            Return strHTML
        End Function
        Public Overrides Function GetBankClick(ByVal PortalID As Integer, ByVal Request As System.Web.HttpRequest) As Boolean
            'test if button has been clicked
            If Not Request.Form.Item("PAGSEGUROGATEWAY.x") Is Nothing Then
                Return True
            Else
                Return False
            End If
        End Function
        Public Overrides Sub AutoResponse(ByVal PortalID As Integer, ByVal Request As System.Web.HttpRequest)

            Try
                'Variaveis locais
                Dim credentials As AccountCredentials
                Dim PagSeguroID As String = String.Empty
                Dim OrderStatusID As Integer
                Dim strPagSeguroStoreOrderID As String = String.Empty


                Dim Token As String = String.Empty
                Dim Pagina As String = String.Empty
                Dim GatewayParams As String = String.Empty
                Dim resultadoValidacao As String = String.Empty
                Dim objSCtrl As New SettingsController
                Dim objOCtrl As New OrderController
                Dim objPCtrl As New ProductController
                Dim objOInfo As NB_Store_OrdersInfo
                Dim transaction1 As Transaction
                Dim setParams As Hashtable
                Dim notification1 As String = String.Empty
                Dim iReference As Integer


                'Loga dados recebidos
                'UpdateLog("AutoResponse HttpMethod: " & Request.HttpMethod)
                'For Each key As String In Request.Form
                ' UpdateLog("AutoResponse Key: " & key & " Value: " & Request.Form(key))
                ' Next
                'UpdateLog("AutoResponse QueryString")
                'For Each Item In Request.QueryString
                'UpdateLog("AutoResponse Key: " & Item & " Value: " & Request.QueryString(Item))
                'Next

                'recebe parametros gravados na loja
                GatewayParams = GetStoreSetting(PortalID, "PagSeguro.gateway", "None")
                If GatewayParams <> "" Then
                    'Parse the gateway setttings into a Hashtable for easy access.
                    setParams = createSettingsTable(GatewayParams)
                    Token = setParams("Token") ' URL that the payment provider will return the client to.
                    Pagina = setParams("Pagina")
                    PagSeguroID = setParams("Email_Cobranca") 'ID of the merchant who the payment is for.
                End If

                'resultadoValidacao = ValidaUOL(Pagina, Token)
                Try
                    credentials = New AccountCredentials(PagSeguroID, Token)
                    notification1 = Request.Form("notificationCode")

                    'UpdateLog("PagSeguroID " + PagSeguroID)
                    'UpdateLog("notification1 " + notification1)
                    'UpdateLog("Token " + Token)

                    If Not String.IsNullOrEmpty(notification1) Then

                        transaction1 = NotificationService.CheckTransaction(credentials, notification1)
                        'UpdateLog("transaction1 status " + transaction1.TransactionStatus.ToString())

                        iReference = Convert.ToInt32(transaction1.Reference)

                        'Status NBStore
                        '<option value="10">Incomplete</option>
                        '				<option value="20">Waiting for Bank</option>
                        '				<option value="30">Cancelled</option>
                        '				<option value="40">Payment OK</option>
                        '				<option selected="selected" value="45">Payment not verified</option>
                        '				<option value="50">Shipped</option>
                        '				<option value="60">Waiting</option>
                        '				<option value="70">Closed</option>
                        '				<option value="75">Archived</option>
                        '				<option value="80">Waiting for Cheque</option>
                        '				<option value="90">Waiting for Payment</option>
                        '				<option value="100">Waiting for Stock</option>

                        ' Status pagseguro
                        '1	Aguardando pagamento: o comprador iniciou a transação, mas até o momento o PagSeguro não recebeu nenhuma informação sobre o pagamento.
                        '2	Em análise: o comprador optou por pagar com um cartão de crédito e o PagSeguro está analisando o risco da transação.
                        '3	Paga: a transação foi paga pelo comprador e o PagSeguro já recebeu uma confirmação da instituição financeira responsável pelo processamento.
                        '4	Disponível: a transação foi paga e chegou ao final de seu prazo de liberação sem ter sido retornada e sem que haja nenhuma disputa aberta.
                        '5	Em disputa: o comprador, dentro do prazo de liberação da transação, abriu uma disputa.
                        '6	Devolvida: o valor da transação foi devolvido para o comprador.
                        '7	Cancelada: a transação foi cancelada sem ter sido finalizada.

                        If transaction1.TransactionStatus = 1 Then '"Aguardando Pagto" 
                            OrderStatusID = 90
                        ElseIf transaction1.TransactionStatus = 2 Then 'Em Analise
                            OrderStatusID = 60
                        ElseIf transaction1.TransactionStatus = 3 Then 'Paga
                            OrderStatusID = 40
                        ElseIf transaction1.TransactionStatus = 4 Then 'Disponivel
                            OrderStatusID = 70
                        ElseIf transaction1.TransactionStatus = 5 Then 'Em disputa
                            OrderStatusID = 90
                        ElseIf transaction1.TransactionStatus = 6 Then 'Devolvido
                            OrderStatusID = 30
                        ElseIf transaction1.TransactionStatus = 7 Then 'Cancelada
                            OrderStatusID = 30
                        Else
                            OrderStatusID = 60 'Qualquer erro inesperado do pagseguro
                        End If

                        ' This section updates the order.
                        objOInfo = objOCtrl.GetOrder(iReference)
                        If Not objOInfo Is Nothing Then
                            'check that the order is valid. (Not yet been processed)
                            If Not objOInfo.OrderIsPlaced Then
                                ' check if order has already been processed
                                If Not objOInfo.OrderIsPlaced Then
                                    'remove qty in trans
                                    objPCtrl.UpdateStockLevel(objOInfo.OrderID)
                                    'set order status to Payed
                                    objOInfo.OrderStatusID = OrderStatusID
                                    Dim UsrID As Integer = objOInfo.UserID
                                    If UsrID = -1 Then UsrID = 0
                                    objOInfo.OrderNumber = Format(PortalID, "00") & "-" & UsrID.ToString("0000#") & "-" & objOInfo.OrderID.ToString("0000#") & "-" & objOInfo.OrderDate.ToString("yyyyMMdd")
                                    objOInfo.OrderIsPlaced = True

                                    objOCtrl.UpdateObjOrder(objOInfo)
                                    'Send email confirmation
                                    SendEmailToClient(PortalID, GetClientEmail(PortalID, objOInfo), objOInfo.OrderNumber, objOInfo, "paymentOK.email", "pt-BR")
                                    SendEmailToManager(PortalID, objOInfo.OrderNumber, objOInfo, "paymentOK.email")


                                End If
                            Else
                                'check if order has already been cancelled
                                If Not objOInfo.OrderStatusID = 30 Then
                                    'remove qty in trans
                                    objPCtrl.RemoveModelQtyTrans(objOInfo.OrderID)
                                    'set order status to cancelled
                                    objOInfo.OrderStatusID = 30
                                    objOCtrl.UpdateObjOrder(objOInfo)
                                End If
                            End If
                        End If

                    End If

                Catch ex As Exception
                    DotNetNuke.Services.Exceptions.LogException(ex) 'something went wrong, lets log the error...
                    SendEmailToAdministrator(0, "AutoResponse ERROR", ex.ToString)

                End Try

                'UpdateLog("resultadoValidacao " + resultadoValidacao)

                'o método POST indica que a requisição é o retorno da validação NPI.
                'Dim strStatusTransacao As String = Request.Form("StatusTransacao")


                'If Trim(strStatusTransacao) = "Completo" Then
                '    OrderStatusID = 40
                'ElseIf Trim(strStatusTransacao) = "Aguardando Pagto" Then
                '    OrderStatusID = 90
                'ElseIf Trim(strStatusTransacao) = "Aprovado" Then
                '    OrderStatusID = 20
                'ElseIf Trim(strStatusTransacao) = "Em Análise" Then
                '    OrderStatusID = 45
                'ElseIf Trim(strStatusTransacao) = "Cancelado" Then
                '    OrderStatusID = 30
                'Else
                '    OrderStatusID = 10
                'End If
                '                OrderStatusID = 90



                ' ------------------------------------------------------------------------
                ' In this case the payment provider passes back data via form POST.
                ' Get the data we need.
                'strPagSeguroStoreOrderID = Request.Form("ProdID_1")


                'Dim PagSeguroStoreOrderID As Integer = CInt(Request.Form("ProdID_1"))
                'Dim PagSeguroCartID As Integer = CInt(Request.Form("PagSeguroOption1"))
                'Dim PagSeguroClientLang As Integer = CInt(Request.Form("PagSeguroOption2"))

                ' ------------------------------------------------------------------------

            Catch ex As Exception
                DotNetNuke.Services.Exceptions.LogException(ex) 'something went wrong, lets log the error...
                SendEmailToAdministrator(PortalID, "AutoResponse ERROR", ex.ToString)
            End Try
        End Sub

        Public Overrides Function GetCompletedHtml(ByVal PortalID As Integer, ByVal UserID As Integer, ByVal Request As System.Web.HttpRequest) As String

            Dim objSCtrl As New SettingsController
            Dim objOCtrl As New OrderController
            Dim objPCtrl As New ProductController
            Dim objCInfo As NB_Store_CartInfo
            Dim objOInfo As NB_Store_OrdersInfo
            Dim objSInfo As NB_Store_SettingsTextInfo
            Dim ordID As Integer = -1
            Dim rtnMsg As String = ""

            UpdateLog("GetCompletedHtml HttpMethod: " & Request.HttpMethod)
            For Each key As String In Request.Form
                UpdateLog("Key: " & key & " Value: " & Request.Form(key))
            Next
            UpdateLog("GetCompletedHtml QueryString")
            For Each Item In Request.QueryString
                UpdateLog("GetCompletedHtml Key: " & Item & " Value: " & Request.QueryString(Item))
            Next

            objCInfo = CurrentCart.GetCurrentCart(PortalID)

            'Get the order id back from the url.
            'ordID = Request.QueryString("ordID")
            ordID = objCInfo.OrderID
            'set rtnMsg to security warning message.
            objSInfo = objSCtrl.GetSettingsText(PortalID, "paymentSECURITY.text", "pt-BR")
            rtnMsg = objSInfo.SettingText
            If IsNumeric(ordID) Then
                objOInfo = objOCtrl.GetOrder(ordID)
                If Not objOInfo Is Nothing Then
                    'Here we make sure that the user trying to view the order is the same as the user that placed the order.
                    'If this is not the case, then we want to display the security warning.
                    If objOInfo.UserID = UserID Then
                        'The user is OK, so continue to pocess the order.
                        ' In most circustances the order will already have been processed by the autoresponse function.
                        ' However it's always good practise to check this and process the order if it has not been done already.
                        'set completed order message
                        objSInfo = objSCtrl.GetSettingsText(PortalID, "paymentOK.text", "pt-BR")

                        rtnMsg = objSInfo.SettingText
                        'Do Token Replacement
                        Dim objTR As New TokenStoreReplace(objOInfo, GetMerchantCulture(PortalID))
                        rtnMsg = objTR.DoTokenReplace(rtnMsg)
                    End If
                End If
            End If

            Return rtnMsg
        End Function
        Public Overrides Sub SetBankRemotePost(ByVal PortalID As Integer, ByVal OrderID As Integer, ByVal Lang As String, ByVal Request As System.Web.HttpRequest)


            Dim Token As String = ""
            ' RemotePost class from NB_Store, this generates the re-direct html required.
            Dim RPost As New RemotePost
            Dim GatewayParams As String
            Dim setParams As Hashtable
            Dim returnURL As String
            Dim cancelURL As String
            Dim PagSeguroURL As String
            Dim notifyURL As String
            Dim PagSeguroID As String
            Dim PagSeguroCartName As String
            Dim PagSeguroButtonURL As String
            Dim PagSeguroCurrency As String
            Dim PagSeguroType As String
            Dim objOCtrl As New OrderController
            Dim objPCtrl As New ProductController
            Dim oInfo As NB_Store_OrdersInfo
            Dim gatewayImg As String
            Dim credentials As AccountCredentials
            Dim objCInfo As NB_Store_CartInfo
            Dim payment As PaymentRequest
            Dim valorTotalPedido As Decimal
            Dim valorFormatado As String
            Dim objAInfo As NB_Store_AddressInfo
            Dim AddrCookie As HttpCookie
            Dim paymentRedirectUri As Uri
            Dim emailComprador As String
            Dim nomeComprador As String

            'Get the gateway settings from the store setting Database
            UpdateLog("SetBankRemotePost Entrei")

            GatewayParams = GetStoreSetting(PortalID, "PagSeguro.gateway", "None")
            If GatewayParams <> "" Then
                'Parse the gateway setttings into a Hashtable for easy access.
                setParams = createSettingsTable(GatewayParams)
                '-------------------------------------------------
                'Get the basic required data from the settings.
                ' with the exception of the ReturnNotifyURL, these parameters are usually always required, by a payment provider
                ' Obviously they may have different names depending on the provider.
                returnURL = setParams("ReturnURL") ' URL that the payment provider will return the client to.
                cancelURL = setParams("ReturnCancelURL") ' URL to return the client if the payment failed.
                PagSeguroURL = setParams("paymentURL") ' URL of the payment provider, where the client will be redirected so they can pay.
                notifyURL = setParams("ReturnNotifyURL") ' URL of the Auto Response, to update the order data in the store.
                PagSeguroID = setParams("Email_Cobranca") 'ID of the merchant who the payment is for.
                Token = setParams("Token") ' URL that the payment provider will return the client to.
                '-------------------------------------------------
                '-------------------------------------------------
                ' Get any other needed parameters.
                'These requirement of these parameters may differ, depending on the payment provider.
                PagSeguroCartName = setParams("CartName")
                PagSeguroButtonURL = setParams("ButtonImageURL")
                PagSeguroCurrency = setParams("Moeda")
                PagSeguroType = setParams("Tipo")
                '-------------------------------------------------
                'Get the order we want to pay for.

                oInfo = objOCtrl.GetOrder(OrderID)


                If Not oInfo Is Nothing Then

                    oInfo.PayType = "PAGSEGURO"
                    '-------------------------------------------------
                    'The URL taken from the settings have tokens included for certain values.
                    'We need to replace these tokens with the actual values from the order.
                    returnURL = Replace(returnURL, "[ORDERID]", oInfo.OrderID.ToString)
                    cancelURL = Replace(cancelURL, "[ORDERID]", oInfo.OrderID.ToString)
                    notifyURL = Replace(notifyURL, "[ORDERID]", oInfo.OrderID.ToString)
                    '-------------------------------------------------
                    'get the cart name to use as a unique item_name.
                    ' this is not usually needed, but I place it here as an example of replacing a token in a setting.
                    PagSeguroCartName = Replace(PagSeguroCartName, "[CARTID]", CurrentCart.GetCurrentCart(PortalID).CartID)
                    'update stock transaction in progress

                    objPCtrl.UpdateModelQtyTrans(oInfo.OrderID)
                    'set order status to redirect to bank
                    oInfo.OrderStatusID = 20
                    objOCtrl.UpdateObjOrder(oInfo)
                    'get the gateway processing image we're going to display while connecting to the payment provider.
                    gatewayImg = GetStoreSetting(PortalID, "gateway.loadimage", "None")


                    credentials = New AccountCredentials(PagSeguroID, Token)
                    Try
                        objCInfo = CurrentCart.GetCurrentCart(PortalID)
                        payment = New PaymentRequest()

                        payment.Currency = Currency.Brl

                        valorTotalPedido = oInfo.CartTotal + oInfo.ShippingCost
                        valorFormatado = Replace(valorTotalPedido.ToString("0.00"), ",", ".")

                        payment.Items.Add(New Item(oInfo.OrderID.ToString(), "Pedido_" & oInfo.OrderID.ToString(), 1, valorTotalPedido))

                        payment.Reference = oInfo.OrderID.ToString()
                        payment.Shipping = New Shipping()
                        payment.Shipping.ShippingType = ShippingType.NotSpecified
                        objAInfo = objOCtrl.GetOrderAddress(oInfo.BillingAddressID)

                        'payment.Shipping.Address = createUOLAddress(objAInfo)
                        payment.Shipping.Cost = 0
                        AddrCookie = getStoreCookie(PortalID, CurrentCart.getCartID(PortalID))


                        'emailComprador = HttpUtility.UrlDecode((getStoreCookieValue(PortalID, AddrCookie, "Email").ToString()))
                        'emailComprador = "silvanabellone@ig.com.br"
                        'nomeComprador = objAInfo.AddressName + " " + objAInfo.AddressName2
                        'payment.Sender = createUOLSender(nomeComprador, emailComprador, objAInfo.Phone1)
                        ServicePointManager.ServerCertificateValidationCallback = Function() True

                        paymentRedirectUri = PaymentService.Register(credentials, payment)

                        UpdateLog(paymentRedirectUri.ToString())

                        RPost = New RemotePost
                        RPost.Url = paymentRedirectUri.ToString()

                        objCInfo.BankHtmlRedirect = RPost.GetPostHtml(gatewayImg)

                        ''Save this data on the cart.
                        CurrentCart.Save(objCInfo)



                    Catch ex As Exception
                        DotNetNuke.Services.Exceptions.LogException(ex) 'something went wrong, lets log the error...
                        SendEmailToAdministrator(PortalID, "PagSeguro AutoReturn ERROR", ex.ToString)
                    Finally

                    End Try
                    '                    // TODO: Substitute the parameters below with your credentials
                    'AccountCredentials credentials = new AccountCredentials("your@email.com", "your_token_here");

                    '        Try
                    '{
                    '    PaymentRequest payment = new PaymentRequest();
                    '    payment.Currency = Currency.Brl;

                    '    payment.Items.Add(new Item("0001", "Notebook Prata", 1, 2430, 1000, 0));
                    '    payment.Items.Add(new Item("0002", "Notebook Rosa", 2, 2560, 750, 0));

                    '    payment.Reference = "REF1234";
                    '    payment.Shipping = new Shipping();
                    '    payment.Shipping.ShippingType = ShippingType.Sedex;
                    '    payment.Shipping.Address = new Address("BRA", "SP", "Sao Paulo", "Jardim Paulistano", "01452002", "Av. Brig. Faria Lima", "1384", "5o andar");
                    '    payment.Shipping.Cost = 13.00m;
                    ' a   payment.Sender = new Sender("Joao Comprador", "comprador@uol.com.br", new Phone("11", "56273440"));
                    '    ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

                    '    Uri paymentRedirectUri = PaymentService.Register(credentials, payment);

                    '    Console.WriteLine(paymentRedirectUri);
                    '}
                    'catch (PagSeguroServiceException exception)
                    '{
                    '    if (exception.StatusCode == HttpStatusCode.Unauthorized)
                    '    {
                    '        Console.WriteLine("Unauthorized: please verify if the credentials used in the web service call are correct.\n");
                    '    }

                    '    Console.WriteLine(exception);
                    '}



                    'Now assign the values we need to the RemotePost class, ready to build the re-direct html.
                    'RPost = New RemotePost
                    'RPost.Url = PagSeguroURL



                    ''reformmatting of the amounts may be required, depnding on language settings and the needs of the provider.
                    ''  <Tipo>CBR</Tipo>
                    ''  <Moeda>BRL</Moeda>
                    ''  <Item_Id>12345</Item_Id>
                    ''  <Item_Descr>Pedido da Loja x</Item_Descr>
                    ''  <Item_Quant>1</Item_Quant>
                    ''  <Item_Valor>100</Item_Valor>
                    ''  <frete>0</frete>
                    ''  <peso>0</peso>
                    'RPost.Add("PagSeguroReturnURL", returnURL)
                    ''RPost.Add("PagSeguroTrxnNumber", oInfo.OrderID.ToString)
                    ''RPost.Add("PagSeguroOption1", CurrentCart.GetCurrentCart(PortalID).CartID)
                    ''RPost.Add("PagSeguroOption2", Lang)
                    ''-------------------------------------------------

                    'RPost.Add("receiverEmail", PagSeguroID)
                    ''RPost.Add("token", Token)
                    'RPost.Add("currency", PagSeguroCurrency)
                    'RPost.Add("itemId1", HTTPPOSTEncode(oInfo.OrderID.ToString))
                    'RPost.Add("itemDescription1", HTTPPOSTEncode("Pedido_" & oInfo.OrderID.ToString))
                    'UpdateLog("SetBankRemotePost CartTotal = " & oInfo.CartTotal.ToString("0.00"))
                    'Dim valorTotalPedido As Decimal = oInfo.CartTotal + oInfo.ShippingCost
                    'Dim valorFormatado As String = Replace(valorTotalPedido.ToString("0.00"), ",", ".")
                    'UpdateLog("SetBankRemotePost valorFormatado = " & valorFormatado)

                    'RPost.Add("itemAmount1", HTTPPOSTEncode(valorFormatado))
                    'RPost.Add("itemQuantity1", "1")

                    'RPost.Add("itemWeight1", "0")

                    ''payPalURL += "?business=" & HTTPPOSTEncode(PayPalID)
                    ''payPalURL += "&item_name=" & HTTPPOSTEncode(PayPalCartName)
                    ''payPalURL += "&item_number=" & HTTPPOSTEncode(oInfo.OrderID.ToString)
                    ''payPalURL += "&custom=" & "pt-BR"()
                    ''payPalURL += "&amount=" & HTTPPOSTEncode(Replace(oInfo.CartTotal.ToString("0.00"), ",", "."))
                    ''payPalURL += "&shipping=" & HTTPPOSTEncode(Replace(oInfo.ShippingCost.ToString("0.00"), ",", "."))
                    ''payPalURL += "&tax=" & HTTPPOSTEncode(Replace(oInfo.AppliedTax.ToString("0.00"), ",", "."))
                    ''payPalURL += "&currency_code=" & HTTPPOSTEncode(PayPalCurrency)
                    ''payPalURL += "&return=" & HTTPPOSTEncode(returnURL)
                    ''payPalURL += "&cancel_return=" & HTTPPOSTEncode(cancelURL)
                    ''payPalURL += "&notify_url=" & HTTPPOSTEncode(notifyURL)

                    ''We are now going to save the re-direct html into the cart data on the database.
                    '' This is because the actual re-direct is done by the checkout module, when it loads.
                    ''Get the cart data from the database.
                    'Dim objCInfo As NB_Store_CartInfo = CurrentCart.GetCurrentCart(PortalID)

                    ''Build and assign the re-direct html to the cart.
                    'objCInfo.BankHtmlRedirect = RPost.GetPostHtml(gatewayImg)
                    ''Save this data on the cart.
                    'CurrentCart.Save(objCInfo)
                    '-------------------------------------------------
                    'Do a log statement of the html created, so we have a trace of what data has been passed.
                    'UpdateLog("SetBankRemotePost PagSeguro HTML = " & objCInfo.BankHtmlRedirect)


                End If
            End If
            'End If ' - This test has been removed in order to support multiple gateways
        End Sub
        Public Function createSettingsTable(ByVal SettingsParams As String) As Hashtable
            Return ParseGateway(SettingsParams)
        End Function

        Public Function ValidaUOL(ByVal Pagina As String, ByVal Token As String) As String

            Dim retorno As String = String.Empty

            Try

                Dim Dados As String = HttpContext.Current.Request.Form.ToString + "&Comando=validar" + "&Token=" + Token

                Dim req As System.Net.HttpWebRequest = DirectCast(System.Net.WebRequest.Create(Pagina), System.Net.HttpWebRequest)

                req.Method = "POST"
                req.ContentLength = Dados.Length
                req.ContentType = "application/x-www-form-urlencoded"

                Dim stOut As New System.IO.StreamWriter(req.GetRequestStream(), System.Text.Encoding.GetEncoding("ISO-8859-1"))
                stOut.Write(Dados)
                stOut.Close()

                Dim stIn As New System.IO.StreamReader(req.GetResponse().GetResponseStream(), System.Text.Encoding.GetEncoding("ISO-8859-1"))
                retorno = stIn.ReadToEnd()
                stIn.Close()

            Catch ex As Exception
                UpdateLog("AutoResponse ValidaUOL ERROR: " + ex.Message)

            Finally
                ValidaUOL = retorno

            End Try

        End Function

        Private Function createUOLAddress(objAInfo As NB_Store_AddressInfo) As Uol.PagSeguro.Address

            Try
                UpdateLog("createUOLAddress Pais: " + "BRA")
                UpdateLog("createUOLAddress Estado: " + objAInfo.RegionCode)
                UpdateLog("createUOLAddress Cidade: " + objAInfo.City)
                UpdateLog("createUOLAddress Bairro: " + objAInfo.CompanyName)
                UpdateLog("createUOLAddress CEP: " + objAInfo.PostalCode)
                UpdateLog("createUOLAddress Endereco: " + objAInfo.Address1)

                Return New Uol.PagSeguro.Address("BRA", objAInfo.RegionCode, objAInfo.City, objAInfo.CompanyName, objAInfo.PostalCode, objAInfo.Address1, "1", "")


            Catch ex As Exception

                DotNetNuke.Services.Exceptions.LogException(ex) 'something went wrong, lets log the error...
                SendEmailToAdministrator(0, "createUOLAddress ERROR", ex.ToString)

                Return Nothing

            End Try

        End Function

        Private Function createUOLSender(pAdressName As String, pEmail As String, pPhone As String) As Sender

            Try

                'payment.Sender = New Sender(objAInfo.AddressName, AddrCookie("Email"), New Phone("", objAInfo.Phone1))
                'payment.Sender = createUOLSender(objAInfo.AddressName, AddrCookie("Email"), New Phone("", objAInfo.Phone1))

                UpdateLog("createUOLSender Nome_Cliente: " + pAdressName)
                UpdateLog("createUOLSender Email: " + pEmail)
                pPhone = "99999999"
                UpdateLog("createUOLSender Fone: " + pPhone)


                Return New Sender(pAdressName, pEmail, New Uol.PagSeguro.Phone("11", pPhone))

            Catch ex As Exception

                DotNetNuke.Services.Exceptions.LogException(ex) 'something went wrong, lets log the error...
                SendEmailToAdministrator(0, "createUOLSender ERROR", ex.ToString)

                Return Nothing
            End Try

        End Function

    End Class
End Namespace